<template>
  <div>
    <div class="operation">
      <div style="margin: 10px 10px">
        <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="title"></el-input>
        <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </div>
      <div style="margin: 10px 0">
        <el-button type="primary" @click="handleAdd">新增<i class="el-icon-circle-plus-outline"></i></el-button>
        <el-popconfirm
            class="ml-5"
            confirm-button-text='确定'
            cancel-button-text='我再想想'
            icon="el-icon-info"
            icon-color="red"
            title="您确定批量删除这些数据吗？"
            @confirm="delBatch"
        >
          <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
        </el-popconfirm>
      </div>
    </div>
    <el-table :data="articleList" border stripe :header-cell-class-name="'headerBg'"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="200" align="center"></el-table-column>
      <el-table-column prop="classid" label="类别" width="80" align="center">

      </el-table-column>
      <el-table-column prop="picurls" label="文章封面" width="140" align="center">
        <template slot-scope="scope">
          <div style="width: 100%; padding-bottom: 56.25%; position: relative;">
            <img style="position: absolute; top: 0; left: 0; width:100%; height:100%; object-fit: cover;"
                 :src="scope.row.picurls"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="文章标题" width="150" align="center"></el-table-column>

      <el-table-column prop="author" label="发布人" width="150" align="center"></el-table-column>
      <el-table-column prop="time" label="发布时间" align="center">
        <template slot-scope="scope">
          {{ formatDate(scope.row.time) }}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="文章内容" width="119" align="center">
        <template slot-scope="scope">
          <el-button @click="view(scope.row.content)" type="primary">查看内容</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除<i class="el-icon-delete"></i></el-button>
          </el-popconfirm>
        </template>
        <!--                <template slot-scope="scope">
                            <el-button type="success" @click="handleEdit(scope.row)" v-if="user.role === 'ROLE_ADMIN'">编辑 <i class="el-icon-edit"></i></el-button>
                            <el-popconfirm
                                    class="ml-5"
                                    confirm-button-text='确定'
                                    cancel-button-text='我再想想'
                                    icon="el-icon-info"
                                    icon-color="red"
                                    title="您确定删除吗？"
                                    @confirm="del(scope.row.id)"
                            >
                                <el-button type="danger" slot="reference" v-if="user.role === 'ROLE_ADMIN'">删除 <i class="el-icon-remove-outline"></i></el-button>
                            </el-popconfirm>
                        </template>-->
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="文章信息" :visible.sync="dialogFormVisible" width="60%">
      <el-form label-width="80px" size="small">
        <el-form-item label="文章标题">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章类别">
          <el-input v-model="form.classid" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="发布时间">-->
        <!--          <el-input v-model="form.time" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="文章内容">
          <mavon-editor ref="md" v-model="form.content" :ishljs="true" @imgAdd="imgAdd"></mavon-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="文章信息" :visible.sync="viewDialogVis" width="60%">
      <el-card>
        <div>
          <mavon-editor
              class="md"
              :value="content"
              :subfield="false"
              :defaultOpen="'preview'"
              :toolbarsFlag="false"
              :editable="false"
              :scrollStyle="true"
              :ishljs="true"
          />
        </div>
      </el-card>
    </el-dialog>

  </div>
</template>

<script>

import axios from "axios";

export default {
  name: "Article",
  data() {
    return {
      form: {},
      tableData: [],
      name: '',
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      teachers: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      content: '',
      viewDialogVis: false,
      articleList: [],
      author: '',
      title: '',
      time: '',
      classid: '',
      picture: [],
      id: ""
    }
  },
  created() {
    this.load();
    console.log("部署--------------", process.env.NODE_ENV)
  },
  methods: {
    formatDate(timestamp) {
      const date = new Date(timestamp);  // 将时间戳转为Date对象，注意JavaScript的时间戳是以毫秒为单位的，所以需要乘以1000
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');  // 月份从0开始，所以需要+1，然后使用padStart确保月份始终是两位数
      const day = String(date.getDate()).padStart(2, '0');  // 使用padStart确保日期始终是两位数
      return `${year}-${month}-${day}`;
    },
    view(content) {
      this.content = content
      this.viewDialogVis = true
    },
    // 绑定@imgAdd event
    imgAdd(pos, $file) {
      let $vm = this.$refs.md
      // 第一步.将图片上传到服务器.
      const formData = new FormData();
      formData.append('file', $file);
      axios({
        url: this.$e.Url + '/Files/upload',
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'},
      }).then((res) => {
        console.log("buyunhao", res);
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        /**
         * $vm 指为mavonEditor实例，可以通过如下两种方式获取
         * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
         * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
         */
        let imgUrl = `<img src="${res.data.result}"/>`;// 将res.data.data包装为<img src='...'/>
        $vm.$img2Url(pos, imgUrl);
        if (this.form.picurls == null)//如果文章没封面的话，将上传图片作为封面【第一次上传文章必须要有封面】
          this.form.picurls = res.data.result;
      })
    },
    getData() {
      axios({
        method: "GET",
        url: this.$e.Url + "/article/FindAll",
      }).then((res) => {
        console.log("请求API接口【/article/FindAll】", res);
        this.articleList = res.data;
      })
    },
    changeEnable(row) {
      this.request.post("/article/update", row).then(res => {
        if (res.code === '200') {
          this.$message.success("操作成功")
        }
      })
    },
    handleAdd() {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          this.dialogFormVisible = true
          this.form = {}
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })
    },
    handleEdit(row) {
      /*this.form = JSON.parse(JSON.stringify(row))*/
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          this.form = row
          this.dialogFormVisible = true
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })

    },
    /*save(){
        this.request.post("/user",this.form).then( res =>{
            if(res){
                this.$message.success("保存成功")
                this.dialogFormVisible = false
                this.load()
            }else{
                this.$message.error("保存失败")
            }
        })
    },*/
    del(id) {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          axios.delete(this.$e.Url + "/article/DeleteArticle", {
            params: {
              id: id,
            },
            headers: {
              Authroniation: localStorage.getItem("Token")
            }
          }).then((res) => {
            console.log("请求API接口【/article/DeleteArticle】", res);
            if (res) {
              this.$message.success("删除成功")
            } else {
              this.$message.error("删除失败")
            }
            this.load();
          })
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })


    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {

          let ids = this.multipleSelection.map(v => v.id)  // 获取所有需要删除的id
          let deletePromises = ids.map(id => {  // 将每个删除操作转换为一个Promise
            return axios.delete(this.$e.Url + "/article/DeleteArticle", {
              params: {
                id: id,
              }
            });
          });
          console.log("删除信息", deletePromises)
          Promise.all(deletePromises).then(responses => {  // 等待所有删除操作完成
            // 检查所有删除操作的响应，如果有任何一个响应表示删除失败，则认为批量删除失败
            let success = responses.every(response => response.status === 200);
            if (success) {
              this.$message.success("批量删除成功");
            } else {
              this.$message.error("批量删除失败");
            }
            this.load();
          });
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })

    },
    load() {
      axios.get(this.$e.Url + "/article/Page", {
            params: {
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              title: this.title,
            }
          }
      ).then(res => {
        console.log("请求API接口【/article/Page】", res)
        this.articleList = res.data.data.sort((a, b) => b.time - a.time);
        for (let i = 0; i < this.articleList.length; i++) {
          if (this.articleList[i].classid == 0) this.articleList[i].classid = "疾病诊疗";
          if (this.articleList[i].classid == 1) this.articleList[i].classid = "营养保健";
          if (this.articleList[i].classid == 2) this.articleList[i].classid = "医学科普";
          if (this.articleList[i].classid == 3) this.articleList[i].classid = "互助问答";
          if (this.articleList[i].classid == 4) this.articleList[i].classid = "中医养生";
          if (this.articleList[i].classid == 5) this.articleList[i].classid = "其他";
        }
        // console.log(this.articleList)
        this.total = res.data.total
        /* this.usernameList=res.data;*/
      })
    },
    save() {
      axios.post(this.$e.Url + "/article/UploadArticle", {
            id: this.form.id,
            title: this.form.title,
            content: this.form.content,
            classid: this.form.classid,
            picurls: this.form.picurls,
            author: "admin",
            time: this.form.time,
          }
      ).then(res => {
        console.log(res)
        if (res) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
          this.load()

        }
      })

    },
    reset() {
      this.title = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    download(url) {
      window.open(url)
    },
  }
}
</script>

<style scoped>

</style>
